package com.hustzp.com.xichuangzhu.dao;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.hustzp.com.xichuangzhu.model.Authors;
import com.hustzp.com.xichuangzhu.model.Library;
import com.hustzp.com.xichuangzhu.model.Review;
import com.hustzp.com.xichuangzhu.poetry.model.Works;
import com.hustzp.com.xichuangzhu.utils.DBHelper;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.dao.RawRowMapper;
import com.j256.ormlite.stmt.QueryBuilder;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.List;

/**
 * Copyright (C) 2015 The huimai mobile client Project
 * All right reserved.
 *
 * @author: wuzhimin@huimai365.com
 * @date: 2016/5/27 21:47
 * @Description:
 */
public class LibraryDao {
    private Context context;
    private DBHelper helper;

    public LibraryDao(Context context) {
        this.context = context;
        try {
            helper = DBHelper.getInstance(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Library> getDynasties() {
        try {
            QueryBuilder<Library, Integer> builder = (QueryBuilder<Library, Integer>) helper.getDao(Library.class).queryBuilder();
            builder.orderBy("start_year", true);
            return helper.getDao(Library.class).query(builder.prepare());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Authors> getAuthors() {
        try {
            List<Authors> authorses = helper.getDao(Authors.class).queryForAll();
            return authorses;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Authors> getAuthorsOrderByDynasty(String search) {
        try {
            QueryBuilder<Authors, Integer> builder = (QueryBuilder<Authors, Integer>) helper.getDao(Authors.class).queryBuilder();
            if (!TextUtils.isEmpty(search)) {
                builder.where().like("name", "%" + search + "%");
            }
            builder.orderBy("dynasty", false);
            return helper.getDao(Authors.class).query(builder.prepare());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public List<Authors> getAuthorsOrderByABC(String search) {
        try {
            QueryBuilder<Authors, Integer> builder = (QueryBuilder<Authors, Integer>) helper.getDao(Authors.class).queryBuilder();
            if (!TextUtils.isEmpty(search)) {
                builder.where().like("name", "%" + search + "%");
            }
            builder.orderBy("first_char", true);
            return helper.getDao(Authors.class).query(builder.prepare());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public Authors getAuthors(Works works) {
        Authors collections = null;
        try {
            QueryBuilder<Authors, Integer> builder = (QueryBuilder<Authors, Integer>) helper.getDao(Authors.class).queryBuilder();
            builder.where().eq("id", works.getAuthor_id());
            List<Authors> users = helper.getDao(Authors.class).query(builder.prepare());
            if (users != null && users.size() > 0) {
                collections = users.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return collections;
    }

    public List<Works> getWorks(Works works) {
        try {
            QueryBuilder<Works, Integer> builder = (QueryBuilder<Works, Integer>) helper.getDao(Works.class).queryBuilder();
            builder.where().eq("author_id", works.getAuthor_id());
            builder.orderBy("kind_cn", true);
            List<Works> users = helper.getDao(Works.class).query(builder.prepare());
            return users;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Works> getWorksOrderby(Works works) {
        try {
            String sql = "select *,case kind_cn"
                    + " when '文' then 0"
                    + " when '诗' then 1"
                    + " when '词' then 2"
                    + " when '曲' then 3"
                    + " when '赋' then 4 end as kind_num"
                    + " from works where author_id =" + works.getAuthor_id()
                    + " order by kind_num";
            GenericRawResults results = helper.getDao(Works.class).queryRaw(sql, new RawRowMapper<Works>() {
                @Override
                public Works mapRow(String[] columnNames, String[] resultColumns) throws SQLException {
                    Works works = new Works();
                    for (int i = 0; i < columnNames.length; i++) {
                        try {
                            setValue(works, columnNames[i], resultColumns[i]);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return works;
                }
            });
            List<Works> users = results.getResults();
            return users;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void setValue(Works works, String filedName, String filedValue) throws Exception {
        Class worksCla = (Class) works.getClass();
        Field field = worksCla.getDeclaredField(filedName);
        field.setAccessible(true);
        field.set(works, filedValue);
        field.setAccessible(false);
    }
//    public List<Collections> getCollectioins(CollectionKinds kinds) {
//        try {
//            QueryBuilder<Collections, Integer> builder = (QueryBuilder<Collections, Integer>) helper.getDao(Collections.class).queryBuilder();
//            builder.where().eq("kind_id", kinds.getId());
//            builder.orderBy("show_order", true);
//            List<Collections> users = helper.getDao(Collections.class).query(builder.prepare());
//            return users;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    public Review getQuotesByAuthor(Authors authors) {
        try {
            //此种方式会出现重复数据，NOTIN没有起作用
            QueryBuilder<Review, Integer> builder = (QueryBuilder<Review, Integer>) helper.getDao(Review.class).queryBuilder();
            builder.orderByRaw("RANDOM()").limit(1).where().ne("author_id", authors.getId());
            List<Review> reviews = helper.getDao(Review.class).query(builder.prepare());
            if (reviews.size() > 0) return reviews.get(0);
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
